// src/store/picture.ts
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Picture, UploadPicture } from '@/types/picture'
import { pictureApi } from '@/api/picture'

export const usePictureStore = defineStore('picture', () => {
  const pictures = ref<Picture[]>([])
  const loading = ref(false)

  // 上传图片
  const uploadPicture = async (uploadData: UploadPicture): Promise<Picture> => {
    loading.value = true
    try {
      const newPicture = await pictureApi.uploadPicture(uploadData)
      pictures.value.unshift(newPicture)
      return newPicture
    } finally {
      loading.value = false
    }
  }

  // 获取图片列表
  const fetchPictures = async (): Promise<Picture[]> => {
    loading.value = true
    try {
      const pictureList = await pictureApi.getPictures()
      pictures.value = pictureList
      return pictureList
    } finally {
      loading.value = false
    }
  }

  // 删除图片
  const deletePicture = async (id: string): Promise<void> => {
    await pictureApi.deletePicture(id)
    pictures.value = pictures.value.filter(picture => picture.id !== id)
  }

  // 根据ID获取图片
  const getPictureById = (id: string): Picture | undefined => {
    return pictures.value.find(picture => picture.id === id)
  }

  return {
    pictures,
    loading,
    uploadPicture,
    fetchPictures,
    deletePicture,
    getPictureById
  }
})